<?php

namespace app\common\services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtService
{
    // 密钥
    const SECRET_KEY = 'uqqkKhkp3UGYJRM5LJgPwxF6NvNdZFgT';

    public function getSecretKey()
    {
        return config('app.encrypt_key') ?: self::SECRET_KEY;
    }

    /**
     * 创建token
     *
     * @param int $id
     * @param string $type
     * @param $exp
     * @param array $params
     * @return array
     */
    public function createToken(int $id, string $type, $exp, array $params = [])
    {
        $time = time();
        $host = app('request')->host();
        $params += [
            'iss' => $host,
            'aud' => $host,
            'iat' => $time,
            'nbf' => $time,
            'exp' => $exp,
        ];
        $params['jti'] = [$id, $type];
        $token = JWT::encode($params, $this->getSecretKey(), 'HS256');
        $params['token'] = $token;
        $params['out'] = $exp * 60 * 60;
        return $params;
    }

    /**
     * 解析token
     *
     * @param string $token
     * @return false|\stdClass
     */
    public function decode(string $token)
    {
        if (!$token) {
            return false;
        }
        try {
            return JWT::decode($token, new Key($this->getSecretKey(), 'HS256'));
        } catch (\Exception $e) {
            exception_log('jwt解密失败', $e);
            return false;
        }
    }
}